package com.wk.config;

import com.wk.pojo.User;
import com.wk.service.Userinfoservice;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @program: thesis
 * @description: 用户的Realm, 用于Shiro的组件
 * @author: 王侃
 * @create: 2020-02-13 16:57
 **/
public class UserRealm extends AuthorizingRealm {

    @Autowired
    Userinfoservice userinfoservice;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        System.out.println("授权");
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        //先获得当前用户的对象
        Subject subject= SecurityUtils.getSubject();
        User currentuser=(User) subject.getPrincipal();
        //设置当前用户的极限，从数据库中获取
        info.addStringPermission(currentuser.getRole());
//        System.out.println("123"+currentuser.getRole());
        return info;
    }


    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;
        //连接真实数据库
        User user=userinfoservice.selectbyusername(token.getUsername());
        if(user==null||user.getStatus()==0)//用户验证，如果不存在或状态被禁用，就不通过
            return null;
        //把所获得的对象放入到session中
        Subject currentsubject=SecurityUtils.getSubject();

        Session session=currentsubject.getSession();
        session.setAttribute("loginuser",user);//保存session

        //密码认证:shiro自己解决
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
